package com.witmed.lib_http

import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import okhttp3.Cache
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

object RetrofitManager {

    @JvmField
    var retrofit:Retrofit?=null

    fun getRetrofit():Retrofit{
        if(retrofit==null){
            synchronized(RetrofitManager::class.java){
                if(retrofit==null){
                    val client=OkHttpClient.Builder()
                        .cache(Cache(File(""),10*1024))
                        .connectTimeout(5,TimeUnit.SECONDS)
                        .readTimeout(5,TimeUnit.SECONDS)
                        .writeTimeout(5,TimeUnit.SECONDS)
                        .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                        .addInterceptor(object :Interceptor{
                            override fun intercept(chain: Interceptor.Chain): Response {
                                //chain.request().newBuilder().cacheControl(CacheControl.Builder().maxAge(10,TimeUnit.SECONDS).build())
                                val response=chain.proceed(chain.request())
                                return response
                            }

                        }).build()
                    retrofit=Retrofit.Builder()
                        .baseUrl("http://10.161.9.80:7015/")
                        .client(client)

                        .addConverterFactory(GsonConverterFactory.create())
//                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .build()
                }
            }
        }
        return retrofit!!
    }

    fun getApiService():ApiService{
        Observable.create<Integer> {

        }
            .subscribe(object : Observer<Integer> {
                override fun onSubscribe(d: Disposable?) {
                    TODO("Not yet implemented")
                }

                override fun onError(e: Throwable?) {
                    TODO("Not yet implemented")
                }

                override fun onComplete() {
                    TODO("Not yet implemented")
                }

                override fun onNext(value: Integer?) {
                    TODO("Not yet implemented")
                }

            })
        val apiService= getRetrofit()?.create(ApiService::class.java)
        return apiService!!
    }
}